package com.luoran.bartalks.action;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.beetl.sql.core.engine.PageQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.luoran.bartalks.core.UserContext;
import com.luoran.bartalks.core.ext.Pageable;
import com.luoran.bartalks.entity.BaseInfo;
import com.luoran.bartalks.entity.biz.BtPackingList;
import com.luoran.bartalks.entity.biz.BtPlanDetails;
import com.luoran.bartalks.entity.biz.BtPlanEntry;
import com.luoran.bartalks.entity.biz.BtPlanTemplate;
import com.luoran.bartalks.entity.biz.BtPlanTemplateEntry;
import com.luoran.bartalks.entity.biz.BtProject;
import com.luoran.bartalks.service.IBtCodingRuleService;
import com.luoran.bartalks.service.IBtPackingListService;
import com.luoran.bartalks.service.IBtPlanDetailsService;
import com.luoran.bartalks.service.IBtPlanEntryService;
import com.luoran.bartalks.service.IBtPlanTemplateEntryService;
import com.luoran.bartalks.service.IBtPlanTemplateService;
import com.luoran.bartalks.service.IBtProjectService;
import com.luoran.bartalks.utils.DateFormatUtils;
import com.luoran.bartalks.utils.EnumBillType;

/**
 * 项目计划
 * 
 * @author Json 2018年1月4日 下午6:24:23
 */
@RequestMapping("/plan")
@Controller
public class BtPlanDetailsAction implements Pageable {

	@Autowired
	private IBtPlanDetailsService planDetailsService;

	@Autowired
	private IBtProjectService projectService;

	@Autowired
	private IBtCodingRuleService codingRuleService;

	@Autowired
	private IBtPlanTemplateService planTemplateService;

	@Autowired
	private IBtPlanTemplateEntryService planTemplateEntryService;

	@Autowired
	private IBtPlanEntryService planEntryService;

	@Autowired
	private IBtPackingListService packingListService;

	private static final Logger log = LoggerFactory.getLogger(BtPlanDetailsAction.class);

	@RequestMapping
	public String lookPlanManage() {
		log.info("跳转到>>计划管理页面");
		return "projectPlanManage/addProject";
	}

	@Override
	public PageQuery<? extends BaseInfo> getQueryList(PageQuery<? extends BaseInfo> pageQuery) {
		@SuppressWarnings("unchecked")
		Map<String, String> map = (Map<String, String>) pageQuery.getParas();
		// 如果没有带着项目ID查询的话默认设置项目ID为null.使没有相应的单据回显,
		if (StringUtils.isEmpty(map.get("projectId"))) {
			map.put("projectId", null);
		} else {
			map.put("projectId", map.get("projectId"));
		}
		if (StringUtils.isEmpty(pageQuery.getOrderBy())) {
			pageQuery.setOrderBy("create_time DESC");
		}
		pageQuery.setPageSize(5);// 设置分页记录条数
		return planDetailsService.getQueryList(pageQuery);
	}

	// 生成计划编码
	@RequestMapping("/generatePlanCode")
	@ResponseBody
	public JSONObject getCode() {
		log.info(">>>>生成计划编码");
		return codingRuleService.generateCoding(EnumBillType.PLAN, UserContext.get().getCompanyId());
	}

	// 获取计划模板
	@RequestMapping("/getPlanTemplate")
	@ResponseBody
	public JSONObject getPlanTemplate() {
		JSONObject result = new JSONObject();
		log.info("获取计划模板>>>");
		List<BtPlanTemplate> planTemplates = planTemplateService
				.getPlanTemplateByCompanyId(UserContext.get().getCompanyId());
		if (planTemplates != null && planTemplates.size() > 0) {
			log.info("获取到" + planTemplates.size() + "条计划模板<<");
			result.put("flag", true);
			result.put("planTemplates", planTemplates);
			return result;
		} else {
			log.info("未找到计划模板<<<");
			result.put("flag", false);
			result.put("msg", "未找到计划模板,请添加后再试!");
			return result;
		}
	}

	// 选择模板时触发事件
	@RequestMapping("/getPlanTemplateByTemplateId/{templateId}")
	@ResponseBody
	public JSONObject getPlanTemplateByTemplateId(@PathVariable("templateId") String templateId) {
		JSONObject result = new JSONObject();
		BtPlanTemplate planTemplate = planTemplateService.getBtPlanTemplateById(templateId);
		result.put("planTemplate", planTemplate);
		return result;
	}

	// 添加计划
	@RequestMapping("/addPlan")
	@ResponseBody
	public JSONObject addPlan(HttpServletRequest req) {
		JSONObject result = new JSONObject();
		BtPlanDetails plan = new BtPlanDetails();
		if (StringUtils.isEmpty(req.getParameter("planCode"))) {
			result.put("flag", false);
			result.put("msg", "计划编码不能为空");
			return result;
		}
		if (StringUtils.isEmpty(req.getParameter("templateId"))) {
			result.put("flag", false);
			result.put("msg", "请选择一个计划模板");
			return result;
		}
		if (StringUtils.isEmpty(req.getParameter("remark"))) {
			result.put("flag", false);
			result.put("msg", "请填写计划描述");
			return result;
		}
		if (StringUtils.isEmpty(req.getParameter("startDate"))) {
			result.put("flag", false);
			result.put("msg", "请选择开始日期");
			return result;
		}
		if (StringUtils.isEmpty(req.getParameter("endDate"))) {
			result.put("flag", false);
			result.put("msg", "请选择结束日期");
			return result;
		}
		if (StringUtils.isEmpty(req.getParameter("weekPolicy"))) {
			result.put("flag", false);
			result.put("msg", "请输入周末天数");
			return result;
		}
		if (StringUtils.isEmpty(req.getParameter("holidayPolicy"))) {
			result.put("flag", false);
			result.put("msg", "请输入假日天数");
			return result;
		}
		plan.setCompanyId(UserContext.get().getCompanyId());
		plan.setProjectId(req.getParameter("projectId"));
		plan.setProjectName(req.getParameter("projectName"));
		plan.setPlanCode(req.getParameter("planCode"));
		plan.setTemplateId(req.getParameter("templateId"));
		plan.setRemark(req.getParameter("remark"));// 计划描述
		plan.setStartDate(DateFormatUtils.Str2Date(req.getParameter("startDate")));
		plan.setEndDate(DateFormatUtils.Str2Date(req.getParameter("endDate")));
		plan.setWeekPolicy(Integer.valueOf(req.getParameter("weekPolicy")));
		plan.setHolidayPolicy(Integer.valueOf(req.getParameter("holidayPolicy")));
		// 判断开始时间结束时间的关系
		long startTime = DateFormatUtils.Str2Date(req.getParameter("startDate")).getTime();// 开始时间的毫秒值
		long endTime = DateFormatUtils.Str2Date(req.getParameter("endDate")).getTime();// 结束时间的毫秒值
		if (startTime > endTime) {
			result.put("flag", false);
			result.put("msg", "选择的日期节点不合法,请重新选择");
			return result;
		}
		// 拿到当前选定的计划模板.
		BtPlanTemplate planTemplate = planTemplateService.getPlanTemplateById(req.getParameter("templateId"));
		// 根据计划模板拿到相关属性
		plan.setTransportTypeId(planTemplate.getTransportTypeId());// 运输方式
		plan.setTransportTypeName(planTemplate.getTransportTypeName());
		plan.setTransportTypeCode(planTemplate.getTransportCode());
		plan.setStartPlaceName(planTemplate.getStartPlaceName());// 起始地
		plan.setStartPlaceId(planTemplate.getStartPlaceId());
		plan.setDestinationName(planTemplate.getDestinationName());// 目的地
		plan.setDestinationId(planTemplate.getDestinationId());
		plan.setDistance(planTemplate.getDistance());// 距离
		plan.setCreateTime(new Date());
		String planId = planDetailsService.addPlan(plan);
		if (planId != null) {// 新增计划成功
			// 根据模板id需要获取当前计划模板的途径点,保存到计划途径点表中
			List<BtPlanTemplateEntry> planTemplateEntrys = planTemplateEntryService
					.getBtPlanTemplateEntryByParentId(req.getParameter("templateId"), UserContext.get().getCompanyId());
			log.info("获取到该计划的途径点个数为 [{}] 个", planTemplateEntrys.size());
			for (BtPlanTemplateEntry planTemplateEntry : planTemplateEntrys) {
				BtPlanEntry planEntry = new BtPlanEntry();// 计划途径点对象
				planEntry.setPlanCode(plan.getPlanCode());// 计划编码
				planEntry.setPlanId(planId);// 计划id
				planEntry.setAddressId(planTemplateEntry.getPositionId());// 位置id
				planEntry.setAddressName(planTemplateEntry.getPositionName());// 位置名称
				planEntry.setSign(planTemplateEntry.getSign());// 顺序表示
				planEntry.setDays(planTemplateEntry.getDays());// 耗时天数
				planEntry.setCompanyId(UserContext.get().getCompanyId());
				planEntry.setCreateTime(new Date());
				// 添加到计划途径点
				String planEntryId = planEntryService.addPlanEntry(planEntry, planId);
				if (planEntryId == null) {
					result.put("flag", false);
					result.put("msg", "操作失败!");
					return result;
				}

			}

			result.put("flag", true);
			result.put("msg", "操作成功!");
			result.put("planId", planId);
			return result;
		} else {
			result.put("flag", false);
			result.put("msg", "操作失败!");
			return result;
		}
	}

	// 获取信息
	@RequestMapping("/edit/{id}")
	@ResponseBody
	public JSONObject getItemById(@PathVariable("id") String id) {
		JSONObject result = new JSONObject();
		// 根据id查询计划记录
		log.info(">>>获取当前记录");
		BtPlanDetails plan = planDetailsService.getItemById(id);
		if (plan.getStarted() == 0) {
			result.put("flag", false);
			result.put("msg", "已经启动过的计划不可编辑!");
			return result;
		}
		// 查询计划模板
		log.info(">>>查询计划模板");
		List<BtPlanTemplate> planTemplates = planTemplateService
				.getPlanTemplateByCompanyId(UserContext.get().getCompanyId());
		if (StringUtils.isEmpty(plan) || StringUtils.isEmpty(planTemplates)) {
			result.put("flag", false);
			result.put("msg", "获取信息失败!");
			return result;
		} else {
			result.put("flag", true);
			result.put("msg", plan);
			result.put("planTemplates", planTemplates);
			return result;
		}
	}

	// 更新计划
	@RequestMapping("/updatePlan")
	@ResponseBody
	public JSONObject updatePlan(HttpServletRequest req) {
		JSONObject result = new JSONObject();
		BtPlanDetails plan = new BtPlanDetails();
		if (StringUtils.isEmpty(req.getParameter("planCode"))) {
			result.put("flag", false);
			result.put("msg", "计划编码不能为空");
			return result;
		}
		if (StringUtils.isEmpty(req.getParameter("templateId"))) {
			result.put("flag", false);
			result.put("msg", "请选择一个计划模板");
			return result;
		}
		if (StringUtils.isEmpty(req.getParameter("remark"))) {
			result.put("flag", false);
			result.put("msg", "请填写计划描述");
			return result;
		}
		if (StringUtils.isEmpty(req.getParameter("startDate"))) {
			result.put("flag", false);
			result.put("msg", "请选择开始日期");
			return result;
		}
		if (StringUtils.isEmpty(req.getParameter("endDate"))) {
			result.put("flag", false);
			result.put("msg", "请选择结束日期");
			return result;
		}
		if (StringUtils.isEmpty(req.getParameter("weekPolicy"))) {
			result.put("flag", false);
			result.put("msg", "请输入周末天数");
			return result;
		}
		if (StringUtils.isEmpty(req.getParameter("holidayPolicy"))) {
			result.put("flag", false);
			result.put("msg", "请输入假日天数");
			return result;
		}
		plan.setId(req.getParameter("id"));
		plan.setPlanCode(req.getParameter("planCode"));
		plan.setTemplateId(req.getParameter("templateId"));
		plan.setRemark(req.getParameter("remark"));
		plan.setStartDate(DateFormatUtils.Str2Date(req.getParameter("startDate")));
		plan.setEndDate(DateFormatUtils.Str2Date(req.getParameter("endDate")));
		plan.setWeekPolicy(Integer.valueOf(req.getParameter("weekPolicy")));
		plan.setHolidayPolicy(Integer.valueOf(req.getParameter("holidayPolicy")));
		// 判断开始时间结束时间的关系
		long startTime = DateFormatUtils.Str2Date(req.getParameter("startDate")).getTime();// 开始时间的毫秒值
		long endTime = DateFormatUtils.Str2Date(req.getParameter("endDate")).getTime();// 结束时间的毫秒值
		if (startTime > endTime) {
			result.put("flag", false);
			result.put("msg", "选择的日期节点不合法,请重新选择");
			return result;
		}

		// 拿到当前选定的计划模板.
		BtPlanTemplate planTemplate = planTemplateService.getPlanTemplateById(req.getParameter("templateId"));
		// 根据计划模板拿到相关属性
		plan.setTransportTypeId(planTemplate.getTransportTypeId());// 运输方式
		plan.setTransportTypeName(planTemplate.getTransportTypeName());
		plan.setTransportTypeCode(planTemplate.getTransportCode());
		plan.setStartPlaceName(planTemplate.getStartPlaceName());// 起始地
		plan.setStartPlaceId(planTemplate.getStartPlaceId());
		plan.setDestinationName(planTemplate.getDestinationName());// 目的地
		plan.setDestinationId(planTemplate.getDestinationId());
		plan.setDistance(planTemplate.getDistance());// 距离
		plan.setCreateTime(new Date());
		log.info(">>>更新计划");
		int count = planDetailsService.updatePlan(plan);
		if (count == 1) {

			// 根据模板id需要获取当前计划模板的途径点,保存到计划途径点表中
			List<BtPlanTemplateEntry> planTemplateEntrys = planTemplateEntryService
					.getBtPlanTemplateEntryByParentId(req.getParameter("templateId"), UserContext.get().getCompanyId());
			// 先删除所有计划途径点.
			planEntryService.deletePlanEntryByPlanId(plan.getId(), UserContext.get().getCompanyId());

			for (BtPlanTemplateEntry planTemplateEntry : planTemplateEntrys) {
				BtPlanEntry planEntry = new BtPlanEntry();
				planEntry.setPlanCode(plan.getPlanCode());// 计划编码
				planEntry.setPlanId(plan.getId());// 计划id
				planEntry.setAddressId(planTemplateEntry.getPositionId());// 位置id
				planEntry.setAddressName(planTemplateEntry.getPositionName());// 位置名称
				planEntry.setSign(planTemplateEntry.getSign());// 顺序表示
				planEntry.setDays(planTemplateEntry.getDays());// 耗时天数
				planEntry.setCompanyId(UserContext.get().getCompanyId());
				planEntry.setCreateTime(new Date());

				// 添加到计划途径点
				String planEntryId = planEntryService.addPlanEntry(planEntry, plan.getId());
				if (planEntryId == null) {

					result.put("flag", false);
					result.put("msg", "操作失败!");
					return result;
				}

			}

			result.put("flag", true);
			result.put("msg", "操作成功!");
			return result;
		} else {
			result.put("flag", false);
			result.put("msg", "操作失败!");
			return result;
		}
	}

	// 删除计划之前需要查询计划下是否有箱单.
	@RequestMapping("/searchPackingList/{id}")
	@ResponseBody
	public JSONObject searchPackingList(@PathVariable("id") String planId) {
		JSONObject result = new JSONObject();
		// 根据计划id查询是否有箱单
		List<BtPackingList> packingLists = packingListService.findPackingListByPlanId(planId);
		if (packingLists.size() == 0) {
			result.put("flag", true);
			return result;
		} else {
			result.put("flag", false);
			result.put("msg", "当前计划包含箱单,不能直接删除!");
			return result;
		}
	}

	// 删除计划
	@RequestMapping("/deletePlan/{id}")
	@ResponseBody
	public JSONObject deletePlan(@PathVariable("id") String id) {
		log.info(">>>>删除计划");
		JSONObject result = new JSONObject();
		BtPlanDetails plan = new BtPlanDetails();
		plan.setStatus(5);
		plan.setId(id);

		int count = planDetailsService.deletePlan(plan);
		planEntryService.deletePlanEntryByPlanId(id, UserContext.get().getCompanyId());
		if (count == 1) {
			result.put("flag", true);
			result.put("msg", "操作成功!");
			return result;
		} else {
			result.put("flag", false);
			result.put("msg", "操作失败!");
			return result;
		}
	}

	// 计划启动.暂停
	@RequestMapping("/start")
	@ResponseBody
	public JSONObject startPlan(BtPlanDetails plan) {
		JSONObject obj = new JSONObject();
		if (plan.getStarted() != 0) {
			int count = planDetailsService.updatePlan(plan);
			if (count == 1) {
				obj.put("flag", true);
				obj.put("msg", "操作成功!");
			} else {
				obj.put("flag", false);
				obj.put("msg", "操作失败!");
			}
		} else {
			try {
				BtProject project = new BtProject();
				project.setId(planDetailsService.getItemById(plan.getId()).getProjectId());
				project.setStarted(0);
				planDetailsService.updatePlan(plan);
				projectService.updateTemplateById(project);
				obj.put("flag", true);
				obj.put("msg", "操作成功!");
			} catch (Exception e) {
				e.printStackTrace();
				obj.put("flag", false);
				obj.put("msg", "操作失败!");
			}
		}
		return obj;
	}

}
